package cn.south.campus.business.interceptor;

import cn.south.campus.business.model.bo.LoginContext;
import cn.south.campus.business.model.bo.LoginInfo;
import cn.south.campus.common.cache.CacheService;
import cn.south.campus.common.model.bo.Result;
import cn.south.campus.common.model.enums.CommonEnums;
import cn.south.campus.common.utils.LoggerUtil;
import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 *
 * </p>
 *
 * @author chow
 * @since 2023/3/14 10:12
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private final Logger LOG = LoggerFactory.getLogger(LoginInterceptor.class);

    @Resource
    private CacheService cacheService;

    @Override
    @SuppressWarnings("all")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //判断是否需要拦截（ThreadLocal中是否有用户）
        LoginInfo context = LoginContext.getContext();
        if (context == null) {
            writeResp(response, CommonEnums.NO_LOGIN);
            return false;
        }
        //判断token是否过期
        String token = context.getToken();
        Object cacheObject = cacheService.getCacheObject(token);
        if (cacheObject == null) {
            writeResp(response, CommonEnums.LOGIN_EXPIRE);
            return false;
        }
        LoginInfo loginInfo = JSON.parseObject(cacheObject.toString(), LoginInfo.class);
        if (loginInfo == null) {
            writeResp(response, CommonEnums.LOGIN_EXPIRE);
            return false;
        }
        return true;
    }

    private void writeResp(HttpServletResponse response, CommonEnums enums) {
        try (ServletOutputStream stream = response.getOutputStream()) {
            Result<Void> result = Result.error(enums);
            stream.write(JSON.toJSONString(result).getBytes());
            stream.flush();
        } catch (IOException e) {
            LoggerUtil.error(LOG, e, "登录拦截错误");
        }
    }
}
